// 创建弹框样式
const style = document.createElement('style');
style.textContent = `
.auto-next-dialog {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: rgba(0, 0, 0, 0.9);
    padding: 20px;
    border-radius: 8px;
    color: white;
    z-index: 9999999;
    text-align: center;
}
.auto-next-dialog p {
    margin: 0 0 15px 0;
    font-size: 16px;
}
.countdown {
    color: #ff9800;
    font-weight: bold;
}
.auto-next-buttons {
    display: flex;
    justify-content: center;
    gap: 10px;
}
.auto-next-button {
    padding: 8px 20px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    background: #4CAF50;
    color: white;
}
.cancel-button {
    background: #f44336;
}
.auto-next-toggle {
    position: fixed;
    right: 20px;
    top: 20px;
    padding: 8px 16px;
    background: rgba(0, 0, 0, 0.8);
    color: white;
    border: none;
    border-radius: 20px;
    cursor: pointer;
    z-index: 9999999;
    font-size: 14px;
    display: flex;
    align-items: center;
    transition: all 0.3s;
}
.auto-next-toggle:hover {
    background: rgba(0, 0, 0, 0.9);
}
.auto-next-toggle .status-dot {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    margin-right: 8px;
}
.auto-next-toggle.enabled .status-dot {
    background: #4CAF50;
}
.auto-next-toggle.disabled .status-dot {
    background: #f44336;
}`;

document.head?.appendChild(style);

let isProcessingEnd = false;
let isJustSwitched = false;
let lastVideoTime = 0;
let isEnabled = true; // 默认启用

function showAutoPlayDialog() {
    if (!isEnabled || isProcessingEnd || isJustSwitched) return;
    isProcessingEnd = true;
    console.log('显示弹窗');

    const oldDialog = document.querySelector('.auto-next-dialog');
    if (oldDialog) {
        oldDialog.remove();
    }

    const dialog = document.createElement('div');
    dialog.className = 'auto-next-dialog';
    dialog.innerHTML = `
        <p>是否播放下一集？</p>
        <p>将在 <span class="countdown">3</span> 秒后自动播放</p>
        <div class="auto-next-buttons">
            <button class="auto-next-button">播放下一集</button>
            <button class="auto-next-button cancel-button">取消</button>
        </div>`;
    
    document.body.appendChild(dialog);

    let countdown = 3;
    const countdownElement = dialog.querySelector('.countdown');
    
    const timer = setInterval(() => {
        countdown--;
        countdownElement.textContent = countdown;
        if (countdown <= 0) {
            clearInterval(timer);
            dialog.remove();
            clickNextButton();
        }
    }, 1000);

    dialog.querySelector('.auto-next-button').onclick = () => {
        clearInterval(timer);
        dialog.remove();
        clickNextButton();
    };

    dialog.querySelector('.cancel-button').onclick = () => {
        clearInterval(timer);
        dialog.remove();
        isProcessingEnd = false;
        isJustSwitched = false;
    };
}

function clickNextButton() {
    // 查找所有可能的下一集按钮
    const selectors = [
        '.vp-play-end__control-btn',
        '.vp-img-container img[alt*="下一"]',
        'button[title*="下一"]',
        'button[title*="下集"]',
        '.vp-video-page-card__video-name',
        '.is-playing + .vp-video-page-card'
    ];

    for (let selector of selectors) {
        const elements = document.querySelectorAll(selector);
        for (let element of elements) {
            const text = element.textContent || element.title || '';
            const isNextVideo = text.includes('下一') || 
                              text.includes('下集') || 
                              element.closest('.vp-video-page-card')?.nextElementSibling;

            if (isNextVideo && !text.includes('上一')) {
                console.log('找到下一集按钮:', text);
                isJustSwitched = true;
                setTimeout(() => {
                    isJustSwitched = false;
                }, 3000);
                element.click();
                return true;
            }
        }
    }

    // 尝试查找播放列表中的下一个视频
    const currentVideo = document.querySelector('.is-playing');
    if (currentVideo) {
        const nextVideo = currentVideo.closest('.vp-aside-box__video-card')?.nextElementSibling;
        if (nextVideo) {
            const videoCard = nextVideo.querySelector('.vp-video-page-card');
            if (videoCard) {
                console.log('点击播放列表中的下一个视频');
                isJustSwitched = true;
                setTimeout(() => {
                    isJustSwitched = false;
                }, 3000);
                videoCard.click();
                return true;
            }
        }
    }

    console.log('未找到下一集按钮');
    return false;
}

// 监听视频播放状态
function watchVideoState() {
    const videoCheck = setInterval(() => {
        const video = document.querySelector('video');
        if (video) {
            clearInterval(videoCheck);
            console.log('找到视频元素');

            video.addEventListener('ended', () => {
                console.log('视频播放结束');
                if (!isProcessingEnd && !isJustSwitched) {
                    showAutoPlayDialog();
                }
            });

            video.addEventListener('timeupdate', () => {
                if (video.currentTime <= lastVideoTime) {
                    lastVideoTime = video.currentTime;
                    return;
                }
                lastVideoTime = video.currentTime;

                if (!isProcessingEnd && !isJustSwitched && 
                    video.duration > 0 && 
                    video.currentTime >= video.duration - 0.5) {
                    console.log('视频即将结束');
                    showAutoPlayDialog();
                }
            });

            video.addEventListener('play', () => {
                console.log('视频开始播放');
                setTimeout(() => {
                    isProcessingEnd = false;
                    isJustSwitched = false;
                }, 1000);
            });

            video.addEventListener('seeking', () => {
                lastVideoTime = video.currentTime;
            });

            const player = document.querySelector('.video-js');
            if (player) {
                const observer = new MutationObserver((mutations) => {
                    if (isProcessingEnd || isJustSwitched) return;
                    
                    for (let mutation of mutations) {
                        if (mutation.target.classList.contains('vjs-ended') || 
                            document.querySelector('.vp-play-end')) {
                            console.log('检测到播放结束状态');
                            showAutoPlayDialog();
                            break;
                        }
                    }
                });

                observer.observe(player, {
                    attributes: true,
                    attributeFilter: ['class']
                });
                console.log('已设置播放器状态监听');
            }
        }
    }, 1000);

    setTimeout(() => clearInterval(videoCheck), 60000);
}

// 初始化
function init() {
    isProcessingEnd = false;
    isJustSwitched = false;
    lastVideoTime = 0;
    
    const oldDialog = document.querySelector('.auto-next-dialog');
    if (oldDialog) {
        oldDialog.remove();
    }
    
    watchVideoState();
}

// 页面加载完成后初始化
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
} else {
    init();
}

// 定期检查初始化状态
setInterval(() => {
    const video = document.querySelector('video');
    const player = document.querySelector('.video-js');
    if (video && player && !isProcessingEnd) {
        init();
    }
}, 2000);

// URL变化时重置状态
let lastUrl = location.href;
new MutationObserver(() => {
    if (location.href !== lastUrl) {
        lastUrl = location.href;
        isProcessingEnd = false;
        init();
    }
}).observe(document, {subtree: true, childList: true}); 

// 初始化时检查状态
checkEnabled();

// 检查插件状态
function checkEnabled() {
    chrome.storage.local.get(['enabled'], (result) => {
        isEnabled = result.enabled ?? true;
        console.log('插件状态:', isEnabled ? '已启用' : '已禁用');
    });
}

// 监听存储变化
chrome.storage.onChanged.addListener((changes) => {
    if (changes.enabled) {
        isEnabled = changes.enabled.newValue;
        console.log('插件状态已更改:', isEnabled ? '已启用' : '已禁用');
    }
});